export default {
  namespaced: true,
  state: {
    count: 1,
    cart: JSON.parse(localStorage.cart || '[]')
  },
  mutations: {
    ADD_CART(state, payload) {
      let flag = false
      state.cart.forEach(item => {
        if (item.id === payload.id) {
          item.count += payload.count
          flag = true
        }
      })
      if (!flag) {
        state.cart.push(payload)
      }
      localStorage.cart = JSON.stringify(state.cart)
    },
    CHEKBOX_ALL(state) {
      state.cart.forEach(item => {
        item.completed = !item.completed
      })
    }
  },
  actions: {
    addCart({ commit }, payload) {
      commit('ADD_CART', payload)
    }
  },
  getters: {
    getAllCount(state) {
      let c = 0;
      state.cart.forEach(item => {
        c += item.count
      })
      return c
    },
    getAllPrice(state) {
      let o = 0;
      state.cart.forEach(item => {
        if (item.completed) {
          o += item.count * item.price
        }
      })
      return o
    },
    getAllCheckBox(state) {
      return state.cart.every(item => item.completed)
    }
  }
}